﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using SimpleNotify.ClientLibrary;
using System.Diagnostics;
using System.Windows.Forms;

namespace SimpleNotify.Client.Views
{
    public class StatusViewPresenter
    {
        public IStatusView View { get; set; }
        private ClientLibrary.Client _wrapper;

        public StatusViewPresenter(IStatusView view, ClientLibrary.Client wrapper)
        {
            this.View = view;
            _wrapper = wrapper;
            _wrapper.OnConnectionChanged += new EventHandler<ConnectionChangedEventArgs>(receiver_OnConnectionChanged);
        }

        void receiver_OnConnectionChanged(object sender, ConnectionChangedEventArgs e)
        {
            UpdateConnection(e.IsConnected);
        }

        private void UpdateConnection(bool isConnected)
        {
            if (isConnected)
            {
                this.View.InvokeMethod(new MethodInvoker(delegate()
                {
                    View.SetConnectionActive();
                }));
            }
            else
            {
                this.View.InvokeMethod(new MethodInvoker(delegate()
                {
                    View.SetConnectionInactive();
                }));
            }
        }

        internal void OnLinkClicked()
        {
            Process.Start("http://simplenotify.codeplex.com");
        }

        internal void OnViewReady()
        {
            UpdateConnection(_wrapper.IsConnected);

            string client = String.Format("{0}", Environment.MachineName).ToUpper();
            string server = String.Format("{0}", Properties.Settings.Default.Server).ToUpper();
            Version v = Assembly.GetExecutingAssembly().GetName().Version;
            string version = String.Format("Version {0}.{1} (Build {2})", v.Major, v.Minor, v.Build);

            View.UpdateLabels(client, server, version);
        }

        internal void OnViewClose()
        {
            _wrapper.OnConnectionChanged -= new EventHandler<ConnectionChangedEventArgs>(receiver_OnConnectionChanged);
            StatusView v = (StatusView)this.View;
            v.Close();
        }
    }
}
